home *** CD-ROM | disk | FTP | other *** search
/ Personal Computer World 2009 February / PCWFEB09.iso / Software / Linux / Kubuntu 8.10 / kubuntu-8.10-desktop-i386.iso / casper / filesystem.squashfs / usr / lib / python2.5 / difflib.pyc (.txt) < prev    next >
Python Compiled Bytecode  |  2008-10-29  |  61KB  |  1,805 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.5)
  3.  
  4. '''
  5. Module difflib -- helpers for computing deltas between objects.
  6.  
  7. Function get_close_matches(word, possibilities, n=3, cutoff=0.6):
  8.     Use SequenceMatcher to return list of the best "good enough" matches.
  9.  
  10. Function context_diff(a, b):
  11.     For two lists of strings, return a delta in context diff format.
  12.  
  13. Function ndiff(a, b):
  14.     Return a delta: the difference between `a` and `b` (lists of strings).
  15.  
  16. Function restore(delta, which):
  17.     Return one of the two sequences that generated an ndiff delta.
  18.  
  19. Function unified_diff(a, b):
  20.     For two lists of strings, return a delta in unified diff format.
  21.  
  22. Class SequenceMatcher:
  23.     A flexible class for comparing pairs of sequences of any type.
  24.  
  25. Class Differ:
  26.     For producing human-readable deltas from sequences of lines of text.
  27.  
  28. Class HtmlDiff:
  29.     For producing HTML side by side comparison with change highlights.
  30. '''
  31. __all__ = [
  32.     'get_close_matches',
  33.     'ndiff',
  34.     'restore',
  35.     'SequenceMatcher',
  36.     'Differ',
  37.     'IS_CHARACTER_JUNK',
  38.     'IS_LINE_JUNK',
  39.     'context_diff',
  40.     'unified_diff',
  41.     'HtmlDiff']
  42. import heapq
  43.  
  44. def _calculate_ratio(matches, length):
  45.     if length:
  46.         return 2 * matches / length
  47.     
  48.     return 1
  49.  
  50.  
  51. class SequenceMatcher:
  52.     '''
  53.     SequenceMatcher is a flexible class for comparing pairs of sequences of
  54.     any type, so long as the sequence elements are hashable.  The basic
  55.     algorithm predates, and is a little fancier than, an algorithm
  56.     published in the late 1980\'s by Ratcliff and Obershelp under the
  57.     hyperbolic name "gestalt pattern matching".  The basic idea is to find
  58.     the longest contiguous matching subsequence that contains no "junk"
  59.     elements (R-O doesn\'t address junk).  The same idea is then applied
  60.     recursively to the pieces of the sequences to the left and to the right
  61.     of the matching subsequence.  This does not yield minimal edit
  62.     sequences, but does tend to yield matches that "look right" to people.
  63.  
  64.     SequenceMatcher tries to compute a "human-friendly diff" between two
  65.     sequences.  Unlike e.g. UNIX(tm) diff, the fundamental notion is the
  66.     longest *contiguous* & junk-free matching subsequence.  That\'s what
  67.     catches peoples\' eyes.  The Windows(tm) windiff has another interesting
  68.     notion, pairing up elements that appear uniquely in each sequence.
  69.     That, and the method here, appear to yield more intuitive difference
  70.     reports than does diff.  This method appears to be the least vulnerable
  71.     to synching up on blocks of "junk lines", though (like blank lines in
  72.     ordinary text files, or maybe "<P>" lines in HTML files).  That may be
  73.     because this is the only method of the 3 that has a *concept* of
  74.     "junk" <wink>.
  75.  
  76.     Example, comparing two strings, and considering blanks to be "junk":
  77.  
  78.     >>> s = SequenceMatcher(lambda x: x == " ",
  79.     ...                     "private Thread currentThread;",
  80.     ...                     "private volatile Thread currentThread;")
  81.     >>>
  82.  
  83.     .ratio() returns a float in [0, 1], measuring the "similarity" of the
  84.     sequences.  As a rule of thumb, a .ratio() value over 0.6 means the
  85.     sequences are close matches:
  86.  
  87.     >>> print round(s.ratio(), 3)
  88.     0.866
  89.     >>>
  90.  
  91.     If you\'re only interested in where the sequences match,
  92.     .get_matching_blocks() is handy:
  93.  
  94.     >>> for block in s.get_matching_blocks():
  95.     ...     print "a[%d] and b[%d] match for %d elements" % block
  96.     a[0] and b[0] match for 8 elements
  97.     a[8] and b[17] match for 21 elements
  98.     a[29] and b[38] match for 0 elements
  99.  
  100.     Note that the last tuple returned by .get_matching_blocks() is always a
  101.     dummy, (len(a), len(b), 0), and this is the only case in which the last
  102.     tuple element (number of elements matched) is 0.
  103.  
  104.     If you want to know how to change the first sequence into the second,
  105.     use .get_opcodes():
  106.  
  107.     >>> for opcode in s.get_opcodes():
  108.     ...     print "%6s a[%d:%d] b[%d:%d]" % opcode
  109.      equal a[0:8] b[0:8]
  110.     insert a[8:8] b[8:17]
  111.      equal a[8:29] b[17:38]
  112.  
  113.     See the Differ class for a fancy human-friendly file differencer, which
  114.     uses SequenceMatcher both to compare sequences of lines, and to compare
  115.     sequences of characters within similar (near-matching) lines.
  116.  
  117.     See also function get_close_matches() in this module, which shows how
  118.     simple code building on SequenceMatcher can be used to do useful work.
  119.  
  120.     Timing:  Basic R-O is cubic time worst case and quadratic time expected
  121.     case.  SequenceMatcher is quadratic time for the worst case and has
  122.     expected-case behavior dependent in a complicated way on how many
  123.     elements the sequences have in common; best case time is linear.
  124.  
  125.     Methods:
  126.  
  127.     __init__(isjunk=None, a=\'\', b=\'\')
  128.         Construct a SequenceMatcher.
  129.  
  130.     set_seqs(a, b)
  131.         Set the two sequences to be compared.
  132.  
  133.     set_seq1(a)
  134.         Set the first sequence to be compared.
  135.  
  136.     set_seq2(b)
  137.         Set the second sequence to be compared.
  138.  
  139.     find_longest_match(alo, ahi, blo, bhi)
  140.         Find longest matching block in a[alo:ahi] and b[blo:bhi].
  141.  
  142.     get_matching_blocks()
  143.         Return list of triples describing matching subsequences.
  144.  
  145.     get_opcodes()
  146.         Return list of 5-tuples describing how to turn a into b.
  147.  
  148.     ratio()
  149.         Return a measure of the sequences\' similarity (float in [0,1]).
  150.  
  151.     quick_ratio()
  152.         Return an upper bound on .ratio() relatively quickly.
  153.  
  154.     real_quick_ratio()
  155.         Return an upper bound on ratio() very quickly.
  156.     '''
  157.     
  158.     def __init__(self, isjunk = None, a = '', b = ''):
  159.         '''Construct a SequenceMatcher.
  160.  
  161.         Optional arg isjunk is None (the default), or a one-argument
  162.         function that takes a sequence element and returns true iff the
  163.         element is junk.  None is equivalent to passing "lambda x: 0", i.e.
  164.         no elements are considered to be junk.  For example, pass
  165.             lambda x: x in " \\t"
  166.         if you\'re comparing lines as sequences of characters, and don\'t
  167.         want to synch up on blanks or hard tabs.
  168.  
  169.         Optional arg a is the first of two sequences to be compared.  By
  170.         default, an empty string.  The elements of a must be hashable.  See
  171.         also .set_seqs() and .set_seq1().
  172.  
  173.         Optional arg b is the second of two sequences to be compared.  By
  174.         default, an empty string.  The elements of b must be hashable. See
  175.         also .set_seqs() and .set_seq2().
  176.         '''
  177.         self.isjunk = isjunk
  178.         self.a = None
  179.         self.b = None
  180.         self.set_seqs(a, b)
  181.  
  182.     
  183.     def set_seqs(self, a, b):
  184.         '''Set the two sequences to be compared.
  185.  
  186.         >>> s = SequenceMatcher()
  187.         >>> s.set_seqs("abcd", "bcde")
  188.         >>> s.ratio()
  189.         0.75
  190.         '''
  191.         self.set_seq1(a)
  192.         self.set_seq2(b)
  193.  
  194.     
  195.     def set_seq1(self, a):
  196.         '''Set the first sequence to be compared.
  197.  
  198.         The second sequence to be compared is not changed.
  199.  
  200.         >>> s = SequenceMatcher(None, "abcd", "bcde")
  201.         >>> s.ratio()
  202.         0.75
  203.         >>> s.set_seq1("bcde")
  204.         >>> s.ratio()
  205.         1.0
  206.         >>>
  207.  
  208.         SequenceMatcher computes and caches detailed information about the
  209.         second sequence, so if you want to compare one sequence S against
  210.         many sequences, use .set_seq2(S) once and call .set_seq1(x)
  211.         repeatedly for each of the other sequences.
  212.  
  213.         See also set_seqs() and set_seq2().
  214.         '''
  215.         if a is self.a:
  216.             return None
  217.         
  218.         self.a = a
  219.         self.matching_blocks = None
  220.         self.opcodes = None
  221.  
  222.     
  223.     def set_seq2(self, b):
  224.         '''Set the second sequence to be compared.
  225.  
  226.         The first sequence to be compared is not changed.
  227.  
  228.         >>> s = SequenceMatcher(None, "abcd", "bcde")
  229.         >>> s.ratio()
  230.         0.75
  231.         >>> s.set_seq2("abcd")
  232.         >>> s.ratio()
  233.         1.0
  234.         >>>
  235.  
  236.         SequenceMatcher computes and caches detailed information about the
  237.         second sequence, so if you want to compare one sequence S against
  238.         many sequences, use .set_seq2(S) once and call .set_seq1(x)
  239.         repeatedly for each of the other sequences.
  240.  
  241.         See also set_seqs() and set_seq1().
  242.         '''
  243.         if b is self.b:
  244.             return None
  245.         
  246.         self.b = b
  247.         self.matching_blocks = None
  248.         self.opcodes = None
  249.         self.fullbcount = None
  250.         self._SequenceMatcher__chain_b()
  251.  
  252.     
  253.     def __chain_b(self):
  254.         b = self.b
  255.         n = len(b)
  256.         self.b2j = b2j = { }
  257.         populardict = { }
  258.         for i, elt in enumerate(b):
  259.             if elt in b2j:
  260.                 indices = b2j[elt]
  261.                 if n >= 200 and len(indices) * 100 > n:
  262.                     populardict[elt] = 1
  263.                     del indices[:]
  264.                 else:
  265.                     indices.append(i)
  266.             len(indices) * 100 > n
  267.             b2j[elt] = [
  268.                 i]
  269.         
  270.         for elt in populardict:
  271.             del b2j[elt]
  272.         
  273.         isjunk = self.isjunk
  274.         junkdict = { }
  275.         if isjunk:
  276.             for d in (populardict, b2j):
  277.                 for elt in d.keys():
  278.                     if isjunk(elt):
  279.                         junkdict[elt] = 1
  280.                         del d[elt]
  281.                         continue
  282.                 
  283.             
  284.         
  285.         self.isbjunk = junkdict.has_key
  286.         self.isbpopular = populardict.has_key
  287.  
  288.     
  289.     def find_longest_match(self, alo, ahi, blo, bhi):
  290.         '''Find longest matching block in a[alo:ahi] and b[blo:bhi].
  291.  
  292.         If isjunk is not defined:
  293.  
  294.         Return (i,j,k) such that a[i:i+k] is equal to b[j:j+k], where
  295.             alo <= i <= i+k <= ahi
  296.             blo <= j <= j+k <= bhi
  297.         and for all (i\',j\',k\') meeting those conditions,
  298.             k >= k\'
  299.             i <= i\'
  300.             and if i == i\', j <= j\'
  301.  
  302.         In other words, of all maximal matching blocks, return one that
  303.         starts earliest in a, and of all those maximal matching blocks that
  304.         start earliest in a, return the one that starts earliest in b.
  305.  
  306.         >>> s = SequenceMatcher(None, " abcd", "abcd abcd")
  307.         >>> s.find_longest_match(0, 5, 0, 9)
  308.         (0, 4, 5)
  309.  
  310.         If isjunk is defined, first the longest matching block is
  311.         determined as above, but with the additional restriction that no
  312.         junk element appears in the block.  Then that block is extended as
  313.         far as possible by matching (only) junk elements on both sides.  So
  314.         the resulting block never matches on junk except as identical junk
  315.         happens to be adjacent to an "interesting" match.
  316.  
  317.         Here\'s the same example as before, but considering blanks to be
  318.         junk.  That prevents " abcd" from matching the " abcd" at the tail
  319.         end of the second sequence directly.  Instead only the "abcd" can
  320.         match, and matches the leftmost "abcd" in the second sequence:
  321.  
  322.         >>> s = SequenceMatcher(lambda x: x==" ", " abcd", "abcd abcd")
  323.         >>> s.find_longest_match(0, 5, 0, 9)
  324.         (1, 0, 4)
  325.  
  326.         If no blocks match, return (alo, blo, 0).
  327.  
  328.         >>> s = SequenceMatcher(None, "ab", "c")
  329.         >>> s.find_longest_match(0, 2, 0, 1)
  330.         (0, 0, 0)
  331.         '''
  332.         (a, b, b2j, isbjunk) = (self.a, self.b, self.b2j, self.isbjunk)
  333.         besti = alo
  334.         bestj = blo
  335.         bestsize = 0
  336.         j2len = { }
  337.         nothing = []
  338.         for i in xrange(alo, ahi):
  339.             j2lenget = j2len.get
  340.             newj2len = { }
  341.             for j in b2j.get(a[i], nothing):
  342.                 if j < blo:
  343.                     continue
  344.                 
  345.                 if j >= bhi:
  346.                     break
  347.                 
  348.                 k = newj2len[j] = j2lenget(j - 1, 0) + 1
  349.                 if k > bestsize:
  350.                     besti = (i - k) + 1
  351.                     bestj = (j - k) + 1
  352.                     bestsize = k
  353.                     continue
  354.             
  355.             j2len = newj2len
  356.         
  357.         while besti > alo and bestj > blo and not isbjunk(b[bestj - 1]) and a[besti - 1] == b[bestj - 1]:
  358.             besti = besti - 1
  359.             bestj = bestj - 1
  360.             bestsize = bestsize + 1
  361.         while besti + bestsize < ahi and bestj + bestsize < bhi and not isbjunk(b[bestj + bestsize]) and a[besti + bestsize] == b[bestj + bestsize]:
  362.             bestsize += 1
  363.         while besti > alo and bestj > blo and isbjunk(b[bestj - 1]) and a[besti - 1] == b[bestj - 1]:
  364.             besti = besti - 1
  365.             bestj = bestj - 1
  366.             bestsize = bestsize + 1
  367.         while besti + bestsize < ahi and bestj + bestsize < bhi and isbjunk(b[bestj + bestsize]) and a[besti + bestsize] == b[bestj + bestsize]:
  368.             bestsize = bestsize + 1
  369.         return (besti, bestj, bestsize)
  370.  
  371.     
  372.     def get_matching_blocks(self):
  373.         '''Return list of triples describing matching subsequences.
  374.  
  375.         Each triple is of the form (i, j, n), and means that
  376.         a[i:i+n] == b[j:j+n].  The triples are monotonically increasing in
  377.         i and in j.  New in Python 2.5, it\'s also guaranteed that if
  378.         (i, j, n) and (i\', j\', n\') are adjacent triples in the list, and
  379.         the second is not the last triple in the list, then i+n != i\' or
  380.         j+n != j\'.  IOW, adjacent triples never describe adjacent equal
  381.         blocks.
  382.  
  383.         The last triple is a dummy, (len(a), len(b), 0), and is the only
  384.         triple with n==0.
  385.  
  386.         >>> s = SequenceMatcher(None, "abxcd", "abcd")
  387.         >>> s.get_matching_blocks()
  388.         [(0, 0, 2), (3, 2, 2), (5, 4, 0)]
  389.         '''
  390.         if self.matching_blocks is not None:
  391.             return self.matching_blocks
  392.         
  393.         la = len(self.a)
  394.         lb = len(self.b)
  395.         queue = [
  396.             (0, la, 0, lb)]
  397.         matching_blocks = []
  398.         while queue:
  399.             (alo, ahi, blo, bhi) = queue.pop()
  400.             (i, j, k) = x = self.find_longest_match(alo, ahi, blo, bhi)
  401.             if k:
  402.                 matching_blocks.append(x)
  403.                 if alo < i and blo < j:
  404.                     queue.append((alo, i, blo, j))
  405.                 
  406.                 if i + k < ahi and j + k < bhi:
  407.                     queue.append((i + k, ahi, j + k, bhi))
  408.                 
  409.             j + k < bhi
  410.         matching_blocks.sort()
  411.         i1 = j1 = k1 = 0
  412.         non_adjacent = []
  413.         for i2, j2, k2 in matching_blocks:
  414.             if i1 + k1 == i2 and j1 + k1 == j2:
  415.                 k1 += k2
  416.                 continue
  417.             if k1:
  418.                 non_adjacent.append((i1, j1, k1))
  419.             
  420.             i1 = i2
  421.             j1 = j2
  422.             k1 = k2
  423.         
  424.         if k1:
  425.             non_adjacent.append((i1, j1, k1))
  426.         
  427.         non_adjacent.append((la, lb, 0))
  428.         self.matching_blocks = non_adjacent
  429.         return self.matching_blocks
  430.  
  431.     
  432.     def get_opcodes(self):
  433.         '''Return list of 5-tuples describing how to turn a into b.
  434.  
  435.         Each tuple is of the form (tag, i1, i2, j1, j2).  The first tuple
  436.         has i1 == j1 == 0, and remaining tuples have i1 == the i2 from the
  437.         tuple preceding it, and likewise for j1 == the previous j2.
  438.  
  439.         The tags are strings, with these meanings:
  440.  
  441.         \'replace\':  a[i1:i2] should be replaced by b[j1:j2]
  442.         \'delete\':   a[i1:i2] should be deleted.
  443.                     Note that j1==j2 in this case.
  444.         \'insert\':   b[j1:j2] should be inserted at a[i1:i1].
  445.                     Note that i1==i2 in this case.
  446.         \'equal\':    a[i1:i2] == b[j1:j2]
  447.  
  448.         >>> a = "qabxcd"
  449.         >>> b = "abycdf"
  450.         >>> s = SequenceMatcher(None, a, b)
  451.         >>> for tag, i1, i2, j1, j2 in s.get_opcodes():
  452.         ...    print ("%7s a[%d:%d] (%s) b[%d:%d] (%s)" %
  453.         ...           (tag, i1, i2, a[i1:i2], j1, j2, b[j1:j2]))
  454.          delete a[0:1] (q) b[0:0] ()
  455.           equal a[1:3] (ab) b[0:2] (ab)
  456.         replace a[3:4] (x) b[2:3] (y)
  457.           equal a[4:6] (cd) b[3:5] (cd)
  458.          insert a[6:6] () b[5:6] (f)
  459.         '''
  460.         if self.opcodes is not None:
  461.             return self.opcodes
  462.         
  463.         i = j = 0
  464.         self.opcodes = answer = []
  465.         for ai, bj, size in self.get_matching_blocks():
  466.             tag = ''
  467.             if i < ai and j < bj:
  468.                 tag = 'replace'
  469.             elif i < ai:
  470.                 tag = 'delete'
  471.             elif j < bj:
  472.                 tag = 'insert'
  473.             
  474.             if tag:
  475.                 answer.append((tag, i, ai, j, bj))
  476.             
  477.             i = ai + size
  478.             j = bj + size
  479.             if size:
  480.                 answer.append(('equal', ai, i, bj, j))
  481.                 continue
  482.         
  483.         return answer
  484.  
  485.     
  486.     def get_grouped_opcodes(self, n = 3):
  487.         """ Isolate change clusters by eliminating ranges with no changes.
  488.  
  489.         Return a generator of groups with upto n lines of context.
  490.         Each group is in the same format as returned by get_opcodes().
  491.  
  492.         >>> from pprint import pprint
  493.         >>> a = map(str, range(1,40))
  494.         >>> b = a[:]
  495.         >>> b[8:8] = ['i']     # Make an insertion
  496.         >>> b[20] += 'x'       # Make a replacement
  497.         >>> b[23:28] = []      # Make a deletion
  498.         >>> b[30] += 'y'       # Make another replacement
  499.         >>> pprint(list(SequenceMatcher(None,a,b).get_grouped_opcodes()))
  500.         [[('equal', 5, 8, 5, 8), ('insert', 8, 8, 8, 9), ('equal', 8, 11, 9, 12)],
  501.          [('equal', 16, 19, 17, 20),
  502.           ('replace', 19, 20, 20, 21),
  503.           ('equal', 20, 22, 21, 23),
  504.           ('delete', 22, 27, 23, 23),
  505.           ('equal', 27, 30, 23, 26)],
  506.          [('equal', 31, 34, 27, 30),
  507.           ('replace', 34, 35, 30, 31),
  508.           ('equal', 35, 38, 31, 34)]]
  509.         """
  510.         codes = self.get_opcodes()
  511.         if not codes:
  512.             codes = [
  513.                 ('equal', 0, 1, 0, 1)]
  514.         
  515.         if codes[0][0] == 'equal':
  516.             (tag, i1, i2, j1, j2) = codes[0]
  517.             codes[0] = (tag, max(i1, i2 - n), i2, max(j1, j2 - n), j2)
  518.         
  519.         if codes[-1][0] == 'equal':
  520.             (tag, i1, i2, j1, j2) = codes[-1]
  521.             codes[-1] = (tag, i1, min(i2, i1 + n), j1, min(j2, j1 + n))
  522.         
  523.         nn = n + n
  524.         group = []
  525.         for tag, i1, i2, j1, j2 in codes:
  526.             if tag == 'equal' and i2 - i1 > nn:
  527.                 group.append((tag, i1, min(i2, i1 + n), j1, min(j2, j1 + n)))
  528.                 yield group
  529.                 group = []
  530.                 i1 = max(i1, i2 - n)
  531.                 j1 = max(j1, j2 - n)
  532.             
  533.             group.append((tag, i1, i2, j1, j2))
  534.         
  535.         if group:
  536.             if len(group) == 1:
  537.                 pass
  538.             if not (group[0][0] == 'equal'):
  539.                 yield group
  540.             
  541.  
  542.     
  543.     def ratio(self):
  544.         '''Return a measure of the sequences\' similarity (float in [0,1]).
  545.  
  546.         Where T is the total number of elements in both sequences, and
  547.         M is the number of matches, this is 2.0*M / T.
  548.         Note that this is 1 if the sequences are identical, and 0 if
  549.         they have nothing in common.
  550.  
  551.         .ratio() is expensive to compute if you haven\'t already computed
  552.         .get_matching_blocks() or .get_opcodes(), in which case you may
  553.         want to try .quick_ratio() or .real_quick_ratio() first to get an
  554.         upper bound.
  555.  
  556.         >>> s = SequenceMatcher(None, "abcd", "bcde")
  557.         >>> s.ratio()
  558.         0.75
  559.         >>> s.quick_ratio()
  560.         0.75
  561.         >>> s.real_quick_ratio()
  562.         1.0
  563.         '''
  564.         matches = reduce((lambda sum, triple: sum + triple[-1]), self.get_matching_blocks(), 0)
  565.         return _calculate_ratio(matches, len(self.a) + len(self.b))
  566.  
  567.     
  568.     def quick_ratio(self):
  569.         """Return an upper bound on ratio() relatively quickly.
  570.  
  571.         This isn't defined beyond that it is an upper bound on .ratio(), and
  572.         is faster to compute.
  573.         """
  574.         if self.fullbcount is None:
  575.             self.fullbcount = fullbcount = { }
  576.             for elt in self.b:
  577.                 fullbcount[elt] = fullbcount.get(elt, 0) + 1
  578.             
  579.         
  580.         fullbcount = self.fullbcount
  581.         avail = { }
  582.         availhas = avail.has_key
  583.         matches = 0
  584.         for elt in self.a:
  585.             if availhas(elt):
  586.                 numb = avail[elt]
  587.             else:
  588.                 numb = fullbcount.get(elt, 0)
  589.             avail[elt] = numb - 1
  590.             if numb > 0:
  591.                 matches = matches + 1
  592.                 continue
  593.         
  594.         return _calculate_ratio(matches, len(self.a) + len(self.b))
  595.  
  596.     
  597.     def real_quick_ratio(self):
  598.         """Return an upper bound on ratio() very quickly.
  599.  
  600.         This isn't defined beyond that it is an upper bound on .ratio(), and
  601.         is faster to compute than either .ratio() or .quick_ratio().
  602.         """
  603.         la = len(self.a)
  604.         lb = len(self.b)
  605.         return _calculate_ratio(min(la, lb), la + lb)
  606.  
  607.  
  608.  
  609. def get_close_matches(word, possibilities, n = 3, cutoff = 0.6):
  610.     '''Use SequenceMatcher to return list of the best "good enough" matches.
  611.  
  612.     word is a sequence for which close matches are desired (typically a
  613.     string).
  614.  
  615.     possibilities is a list of sequences against which to match word
  616.     (typically a list of strings).
  617.  
  618.     Optional arg n (default 3) is the maximum number of close matches to
  619.     return.  n must be > 0.
  620.  
  621.     Optional arg cutoff (default 0.6) is a float in [0, 1].  Possibilities
  622.     that don\'t score at least that similar to word are ignored.
  623.  
  624.     The best (no more than n) matches among the possibilities are returned
  625.     in a list, sorted by similarity score, most similar first.
  626.  
  627.     >>> get_close_matches("appel", ["ape", "apple", "peach", "puppy"])
  628.     [\'apple\', \'ape\']
  629.     >>> import keyword as _keyword
  630.     >>> get_close_matches("wheel", _keyword.kwlist)
  631.     [\'while\']
  632.     >>> get_close_matches("apple", _keyword.kwlist)
  633.     []
  634.     >>> get_close_matches("accept", _keyword.kwlist)
  635.     [\'except\']
  636.     '''
  637.     if not n > 0:
  638.         raise ValueError('n must be > 0: %r' % (n,))
  639.     
  640.     if cutoff <= cutoff:
  641.         pass
  642.     elif not cutoff <= 1:
  643.         raise ValueError('cutoff must be in [0.0, 1.0]: %r' % (cutoff,))
  644.     
  645.     result = []
  646.     s = SequenceMatcher()
  647.     s.set_seq2(word)
  648.     for x in possibilities:
  649.         s.set_seq1(x)
  650.         if s.real_quick_ratio() >= cutoff and s.quick_ratio() >= cutoff and s.ratio() >= cutoff:
  651.             result.append((s.ratio(), x))
  652.             continue
  653.         0
  654.     
  655.     result = heapq.nlargest(n, result)
  656.     return [ x for score, x in result ]
  657.  
  658.  
  659. def _count_leading(line, ch):
  660.     """
  661.     Return number of `ch` characters at the start of `line`.
  662.  
  663.     Example:
  664.  
  665.     >>> _count_leading('   abc', ' ')
  666.     3
  667.     """
  668.     i = 0
  669.     n = len(line)
  670.     while i < n and line[i] == ch:
  671.         i += 1
  672.     return i
  673.  
  674.  
  675. class Differ:
  676.     """
  677.     Differ is a class for comparing sequences of lines of text, and
  678.     producing human-readable differences or deltas.  Differ uses
  679.     SequenceMatcher both to compare sequences of lines, and to compare
  680.     sequences of characters within similar (near-matching) lines.
  681.  
  682.     Each line of a Differ delta begins with a two-letter code:
  683.  
  684.         '- '    line unique to sequence 1
  685.         '+ '    line unique to sequence 2
  686.         '  '    line common to both sequences
  687.         '? '    line not present in either input sequence
  688.  
  689.     Lines beginning with '? ' attempt to guide the eye to intraline
  690.     differences, and were not present in either input sequence.  These lines
  691.     can be confusing if the sequences contain tab characters.
  692.  
  693.     Note that Differ makes no claim to produce a *minimal* diff.  To the
  694.     contrary, minimal diffs are often counter-intuitive, because they synch
  695.     up anywhere possible, sometimes accidental matches 100 pages apart.
  696.     Restricting synch points to contiguous matches preserves some notion of
  697.     locality, at the occasional cost of producing a longer diff.
  698.  
  699.     Example: Comparing two texts.
  700.  
  701.     First we set up the texts, sequences of individual single-line strings
  702.     ending with newlines (such sequences can also be obtained from the
  703.     `readlines()` method of file-like objects):
  704.  
  705.     >>> text1 = '''  1. Beautiful is better than ugly.
  706.     ...   2. Explicit is better than implicit.
  707.     ...   3. Simple is better than complex.
  708.     ...   4. Complex is better than complicated.
  709.     ... '''.splitlines(1)
  710.     >>> len(text1)
  711.     4
  712.     >>> text1[0][-1]
  713.     '\\n'
  714.     >>> text2 = '''  1. Beautiful is better than ugly.
  715.     ...   3.   Simple is better than complex.
  716.     ...   4. Complicated is better than complex.
  717.     ...   5. Flat is better than nested.
  718.     ... '''.splitlines(1)
  719.  
  720.     Next we instantiate a Differ object:
  721.  
  722.     >>> d = Differ()
  723.  
  724.     Note that when instantiating a Differ object we may pass functions to
  725.     filter out line and character 'junk'.  See Differ.__init__ for details.
  726.  
  727.     Finally, we compare the two:
  728.  
  729.     >>> result = list(d.compare(text1, text2))
  730.  
  731.     'result' is a list of strings, so let's pretty-print it:
  732.  
  733.     >>> from pprint import pprint as _pprint
  734.     >>> _pprint(result)
  735.     ['    1. Beautiful is better than ugly.\\n',
  736.      '-   2. Explicit is better than implicit.\\n',
  737.      '-   3. Simple is better than complex.\\n',
  738.      '+   3.   Simple is better than complex.\\n',
  739.      '?     ++\\n',
  740.      '-   4. Complex is better than complicated.\\n',
  741.      '?            ^                     ---- ^\\n',
  742.      '+   4. Complicated is better than complex.\\n',
  743.      '?           ++++ ^                      ^\\n',
  744.      '+   5. Flat is better than nested.\\n']
  745.  
  746.     As a single multi-line string it looks like this:
  747.  
  748.     >>> print ''.join(result),
  749.         1. Beautiful is better than ugly.
  750.     -   2. Explicit is better than implicit.
  751.     -   3. Simple is better than complex.
  752.     +   3.   Simple is better than complex.
  753.     ?     ++
  754.     -   4. Complex is better than complicated.
  755.     ?            ^                     ---- ^
  756.     +   4. Complicated is better than complex.
  757.     ?           ++++ ^                      ^
  758.     +   5. Flat is better than nested.
  759.  
  760.     Methods:
  761.  
  762.     __init__(linejunk=None, charjunk=None)
  763.         Construct a text differencer, with optional filters.
  764.  
  765.     compare(a, b)
  766.         Compare two sequences of lines; generate the resulting delta.
  767.     """
  768.     
  769.     def __init__(self, linejunk = None, charjunk = None):
  770.         '''
  771.         Construct a text differencer, with optional filters.
  772.  
  773.         The two optional keyword parameters are for filter functions:
  774.  
  775.         - `linejunk`: A function that should accept a single string argument,
  776.           and return true iff the string is junk. The module-level function
  777.           `IS_LINE_JUNK` may be used to filter out lines without visible
  778.           characters, except for at most one splat (\'#\').  It is recommended
  779.           to leave linejunk None; as of Python 2.3, the underlying
  780.           SequenceMatcher class has grown an adaptive notion of "noise" lines
  781.           that\'s better than any static definition the author has ever been
  782.           able to craft.
  783.  
  784.         - `charjunk`: A function that should accept a string of length 1. The
  785.           module-level function `IS_CHARACTER_JUNK` may be used to filter out
  786.           whitespace characters (a blank or tab; **note**: bad idea to include
  787.           newline in this!).  Use of IS_CHARACTER_JUNK is recommended.
  788.         '''
  789.         self.linejunk = linejunk
  790.         self.charjunk = charjunk
  791.  
  792.     
  793.     def compare(self, a, b):
  794.         """
  795.         Compare two sequences of lines; generate the resulting delta.
  796.  
  797.         Each sequence must contain individual single-line strings ending with
  798.         newlines. Such sequences can be obtained from the `readlines()` method
  799.         of file-like objects.  The delta generated also consists of newline-
  800.         terminated strings, ready to be printed as-is via the writeline()
  801.         method of a file-like object.
  802.  
  803.         Example:
  804.  
  805.         >>> print ''.join(Differ().compare('one\\ntwo\\nthree\\n'.splitlines(1),
  806.         ...                                'ore\\ntree\\nemu\\n'.splitlines(1))),
  807.         - one
  808.         ?  ^
  809.         + ore
  810.         ?  ^
  811.         - two
  812.         - three
  813.         ?  -
  814.         + tree
  815.         + emu
  816.         """
  817.         cruncher = SequenceMatcher(self.linejunk, a, b)
  818.         for tag, alo, ahi, blo, bhi in cruncher.get_opcodes():
  819.             if tag == 'replace':
  820.                 g = self._fancy_replace(a, alo, ahi, b, blo, bhi)
  821.             elif tag == 'delete':
  822.                 g = self._dump('-', a, alo, ahi)
  823.             elif tag == 'insert':
  824.                 g = self._dump('+', b, blo, bhi)
  825.             elif tag == 'equal':
  826.                 g = self._dump(' ', a, alo, ahi)
  827.             else:
  828.                 raise ValueError, 'unknown tag %r' % (tag,)
  829.             for line in g:
  830.                 yield line
  831.             
  832.         
  833.  
  834.     
  835.     def _dump(self, tag, x, lo, hi):
  836.         '''Generate comparison results for a same-tagged range.'''
  837.         for i in xrange(lo, hi):
  838.             yield '%s %s' % (tag, x[i])
  839.         
  840.  
  841.     
  842.     def _plain_replace(self, a, alo, ahi, b, blo, bhi):
  843.         if not alo < ahi or blo < bhi:
  844.             raise AssertionError
  845.         if bhi - blo < ahi - alo:
  846.             first = self._dump('+', b, blo, bhi)
  847.             second = self._dump('-', a, alo, ahi)
  848.         else:
  849.             first = self._dump('-', a, alo, ahi)
  850.             second = self._dump('+', b, blo, bhi)
  851.         for g in (first, second):
  852.             for line in g:
  853.                 yield line
  854.             
  855.         
  856.  
  857.     
  858.     def _fancy_replace(self, a, alo, ahi, b, blo, bhi):
  859.         """
  860.         When replacing one block of lines with another, search the blocks
  861.         for *similar* lines; the best-matching pair (if any) is used as a
  862.         synch point, and intraline difference marking is done on the
  863.         similar pair. Lots of work, but often worth it.
  864.  
  865.         Example:
  866.  
  867.         >>> d = Differ()
  868.         >>> results = d._fancy_replace(['abcDefghiJkl\\n'], 0, 1,
  869.         ...                            ['abcdefGhijkl\\n'], 0, 1)
  870.         >>> print ''.join(results),
  871.         - abcDefghiJkl
  872.         ?    ^  ^  ^
  873.         + abcdefGhijkl
  874.         ?    ^  ^  ^
  875.         """
  876.         (best_ratio, cutoff) = (0.74, 0.75)
  877.         cruncher = SequenceMatcher(self.charjunk)
  878.         (eqi, eqj) = (None, None)
  879.         for j in xrange(blo, bhi):
  880.             bj = b[j]
  881.             cruncher.set_seq2(bj)
  882.             for i in xrange(alo, ahi):
  883.                 ai = a[i]
  884.                 if ai == bj:
  885.                     if eqi is None:
  886.                         eqi = i
  887.                         eqj = j
  888.                         continue
  889.                     continue
  890.                 
  891.                 cruncher.set_seq1(ai)
  892.                 if cruncher.real_quick_ratio() > best_ratio and cruncher.quick_ratio() > best_ratio and cruncher.ratio() > best_ratio:
  893.                     best_ratio = cruncher.ratio()
  894.                     best_i = i
  895.                     best_j = j
  896.                     continue
  897.             
  898.         
  899.         if best_ratio < cutoff:
  900.             if eqi is None:
  901.                 for line in self._plain_replace(a, alo, ahi, b, blo, bhi):
  902.                     yield line
  903.                 
  904.                 return None
  905.             
  906.             best_i = eqi
  907.             best_j = eqj
  908.             best_ratio = 1
  909.         else:
  910.             eqi = None
  911.         for line in self._fancy_helper(a, alo, best_i, b, blo, best_j):
  912.             yield line
  913.         
  914.         aelt = a[best_i]
  915.         belt = b[best_j]
  916.         if eqi is None:
  917.             atags = btags = ''
  918.             cruncher.set_seqs(aelt, belt)
  919.             for tag, ai1, ai2, bj1, bj2 in cruncher.get_opcodes():
  920.                 la = ai2 - ai1
  921.                 lb = bj2 - bj1
  922.                 if tag == 'replace':
  923.                     atags += '^' * la
  924.                     btags += '^' * lb
  925.                     continue
  926.                 if tag == 'delete':
  927.                     atags += '-' * la
  928.                     continue
  929.                 if tag == 'insert':
  930.                     btags += '+' * lb
  931.                     continue
  932.                 if tag == 'equal':
  933.                     atags += ' ' * la
  934.                     btags += ' ' * lb
  935.                     continue
  936.                 raise ValueError, 'unknown tag %r' % (tag,)
  937.             
  938.             for line in self._qformat(aelt, belt, atags, btags):
  939.                 yield line
  940.             
  941.         else:
  942.             yield '  ' + aelt
  943.         for line in self._fancy_helper(a, best_i + 1, ahi, b, best_j + 1, bhi):
  944.             yield line
  945.         
  946.  
  947.     
  948.     def _fancy_helper(self, a, alo, ahi, b, blo, bhi):
  949.         g = []
  950.         if alo < ahi:
  951.             if blo < bhi:
  952.                 g = self._fancy_replace(a, alo, ahi, b, blo, bhi)
  953.             else:
  954.                 g = self._dump('-', a, alo, ahi)
  955.         elif blo < bhi:
  956.             g = self._dump('+', b, blo, bhi)
  957.         
  958.         for line in g:
  959.             yield line
  960.         
  961.  
  962.     
  963.     def _qformat(self, aline, bline, atags, btags):
  964.         '''
  965.         Format "?" output and deal with leading tabs.
  966.  
  967.         Example:
  968.  
  969.         >>> d = Differ()
  970.         >>> results = d._qformat(\'\\tabcDefghiJkl\\n\', \'\\t\\tabcdefGhijkl\\n\',
  971.         ...                      \'  ^ ^  ^      \', \'+  ^ ^  ^      \')
  972.         >>> for line in results: print repr(line)
  973.         ...
  974.         \'- \\tabcDefghiJkl\\n\'
  975.         \'? \\t ^ ^  ^\\n\'
  976.         \'+ \\t\\tabcdefGhijkl\\n\'
  977.         \'? \\t  ^ ^  ^\\n\'
  978.         '''
  979.         common = min(_count_leading(aline, '\t'), _count_leading(bline, '\t'))
  980.         common = min(common, _count_leading(atags[:common], ' '))
  981.         atags = atags[common:].rstrip()
  982.         btags = btags[common:].rstrip()
  983.         yield '- ' + aline
  984.         if atags:
  985.             yield '? %s%s\n' % ('\t' * common, atags)
  986.         
  987.         yield '+ ' + bline
  988.         if btags:
  989.             yield '? %s%s\n' % ('\t' * common, btags)
  990.         
  991.  
  992.  
  993. import re
  994.  
  995. def IS_LINE_JUNK(line, pat = re.compile('\\s*#?\\s*$').match):
  996.     """
  997.     Return 1 for ignorable line: iff `line` is blank or contains a single '#'.
  998.  
  999.     Examples:
  1000.  
  1001.     >>> IS_LINE_JUNK('\\n')
  1002.     True
  1003.     >>> IS_LINE_JUNK('  #   \\n')
  1004.     True
  1005.     >>> IS_LINE_JUNK('hello\\n')
  1006.     False
  1007.     """
  1008.     return pat(line) is not None
  1009.  
  1010.  
  1011. def IS_CHARACTER_JUNK(ch, ws = ' \t'):
  1012.     """
  1013.     Return 1 for ignorable character: iff `ch` is a space or tab.
  1014.  
  1015.     Examples:
  1016.  
  1017.     >>> IS_CHARACTER_JUNK(' ')
  1018.     True
  1019.     >>> IS_CHARACTER_JUNK('\\t')
  1020.     True
  1021.     >>> IS_CHARACTER_JUNK('\\n')
  1022.     False
  1023.     >>> IS_CHARACTER_JUNK('x')
  1024.     False
  1025.     """
  1026.     return ch in ws
  1027.  
  1028.  
  1029. def unified_diff(a, b, fromfile = '', tofile = '', fromfiledate = '', tofiledate = '', n = 3, lineterm = '\n'):
  1030.     '''
  1031.     Compare two sequences of lines; generate the delta as a unified diff.
  1032.  
  1033.     Unified diffs are a compact way of showing line changes and a few
  1034.     lines of context.  The number of context lines is set by \'n\' which
  1035.     defaults to three.
  1036.  
  1037.     By default, the diff control lines (those with ---, +++, or @@) are
  1038.     created with a trailing newline.  This is helpful so that inputs
  1039.     created from file.readlines() result in diffs that are suitable for
  1040.     file.writelines() since both the inputs and outputs have trailing
  1041.     newlines.
  1042.  
  1043.     For inputs that do not have trailing newlines, set the lineterm
  1044.     argument to "" so that the output will be uniformly newline free.
  1045.  
  1046.     The unidiff format normally has a header for filenames and modification
  1047.     times.  Any or all of these may be specified using strings for
  1048.     \'fromfile\', \'tofile\', \'fromfiledate\', and \'tofiledate\'.  The modification
  1049.     times are normally expressed in the format returned by time.ctime().
  1050.  
  1051.     Example:
  1052.  
  1053.     >>> for line in unified_diff(\'one two three four\'.split(),
  1054.     ...             \'zero one tree four\'.split(), \'Original\', \'Current\',
  1055.     ...             \'Sat Jan 26 23:30:50 1991\', \'Fri Jun 06 10:20:52 2003\',
  1056.     ...             lineterm=\'\'):
  1057.     ...     print line
  1058.     --- Original Sat Jan 26 23:30:50 1991
  1059.     +++ Current Fri Jun 06 10:20:52 2003
  1060.     @@ -1,4 +1,4 @@
  1061.     +zero
  1062.      one
  1063.     -two
  1064.     -three
  1065.     +tree
  1066.      four
  1067.     '''
  1068.     started = False
  1069.     for group in SequenceMatcher(None, a, b).get_grouped_opcodes(n):
  1070.         if not started:
  1071.             yield '--- %s %s%s' % (fromfile, fromfiledate, lineterm)
  1072.             yield '+++ %s %s%s' % (tofile, tofiledate, lineterm)
  1073.             started = True
  1074.         
  1075.         (i1, i2, j1, j2) = (group[0][1], group[-1][2], group[0][3], group[-1][4])
  1076.         yield '@@ -%d,%d +%d,%d @@%s' % (i1 + 1, i2 - i1, j1 + 1, j2 - j1, lineterm)
  1077.         for tag, i1, i2, j1, j2 in group:
  1078.             if tag == 'equal':
  1079.                 for line in a[i1:i2]:
  1080.                     yield ' ' + line
  1081.                 
  1082.                 continue
  1083.             
  1084.             if tag == 'replace' or tag == 'delete':
  1085.                 for line in a[i1:i2]:
  1086.                     yield '-' + line
  1087.                 
  1088.             
  1089.             if tag == 'replace' or tag == 'insert':
  1090.                 for line in b[j1:j2]:
  1091.                     yield '+' + line
  1092.                 
  1093.         
  1094.     
  1095.  
  1096.  
  1097. def context_diff(a, b, fromfile = '', tofile = '', fromfiledate = '', tofiledate = '', n = 3, lineterm = '\n'):
  1098.     '''
  1099.     Compare two sequences of lines; generate the delta as a context diff.
  1100.  
  1101.     Context diffs are a compact way of showing line changes and a few
  1102.     lines of context.  The number of context lines is set by \'n\' which
  1103.     defaults to three.
  1104.  
  1105.     By default, the diff control lines (those with *** or ---) are
  1106.     created with a trailing newline.  This is helpful so that inputs
  1107.     created from file.readlines() result in diffs that are suitable for
  1108.     file.writelines() since both the inputs and outputs have trailing
  1109.     newlines.
  1110.  
  1111.     For inputs that do not have trailing newlines, set the lineterm
  1112.     argument to "" so that the output will be uniformly newline free.
  1113.  
  1114.     The context diff format normally has a header for filenames and
  1115.     modification times.  Any or all of these may be specified using
  1116.     strings for \'fromfile\', \'tofile\', \'fromfiledate\', and \'tofiledate\'.
  1117.     The modification times are normally expressed in the format returned
  1118.     by time.ctime().  If not specified, the strings default to blanks.
  1119.  
  1120.     Example:
  1121.  
  1122.     >>> print \'\'.join(context_diff(\'one\\ntwo\\nthree\\nfour\\n\'.splitlines(1),
  1123.     ...       \'zero\\none\\ntree\\nfour\\n\'.splitlines(1), \'Original\', \'Current\',
  1124.     ...       \'Sat Jan 26 23:30:50 1991\', \'Fri Jun 06 10:22:46 2003\')),
  1125.     *** Original Sat Jan 26 23:30:50 1991
  1126.     --- Current Fri Jun 06 10:22:46 2003
  1127.     ***************
  1128.     *** 1,4 ****
  1129.       one
  1130.     ! two
  1131.     ! three
  1132.       four
  1133.     --- 1,4 ----
  1134.     + zero
  1135.       one
  1136.     ! tree
  1137.       four
  1138.     '''
  1139.     started = False
  1140.     prefixmap = {
  1141.         'insert': '+ ',
  1142.         'delete': '- ',
  1143.         'replace': '! ',
  1144.         'equal': '  ' }
  1145.     for group in SequenceMatcher(None, a, b).get_grouped_opcodes(n):
  1146.         if not started:
  1147.             yield '*** %s %s%s' % (fromfile, fromfiledate, lineterm)
  1148.             yield '--- %s %s%s' % (tofile, tofiledate, lineterm)
  1149.             started = True
  1150.         
  1151.         yield '***************%s' % (lineterm,)
  1152.         if group[-1][2] - group[0][1] >= 2:
  1153.             yield '*** %d,%d ****%s' % (group[0][1] + 1, group[-1][2], lineterm)
  1154.         else:
  1155.             yield '*** %d ****%s' % (group[-1][2], lineterm)
  1156.         visiblechanges = _[1]
  1157.         if visiblechanges:
  1158.             for tag, i1, i2, _, _ in group:
  1159.                 if tag != 'insert':
  1160.                     for line in a[i1:i2]:
  1161.                         yield prefixmap[tag] + line
  1162.                         []
  1163.                     
  1164.                 []
  1165.             
  1166.         
  1167.         if group[-1][4] - group[0][3] >= 2:
  1168.             yield '--- %d,%d ----%s' % (group[0][3] + 1, group[-1][4], lineterm)
  1169.         else:
  1170.             yield '--- %d ----%s' % (group[-1][4], lineterm)
  1171.         visiblechanges = _[2]
  1172.         if visiblechanges:
  1173.             for tag, _, _, j1, j2 in group:
  1174.                 if tag != 'delete':
  1175.                     for line in b[j1:j2]:
  1176.                         yield prefixmap[tag] + line
  1177.                         []
  1178.                     
  1179.                 []
  1180.             
  1181.     
  1182.  
  1183.  
  1184. def ndiff(a, b, linejunk = None, charjunk = IS_CHARACTER_JUNK):
  1185.     '''
  1186.     Compare `a` and `b` (lists of strings); return a `Differ`-style delta.
  1187.  
  1188.     Optional keyword parameters `linejunk` and `charjunk` are for filter
  1189.     functions (or None):
  1190.  
  1191.     - linejunk: A function that should accept a single string argument, and
  1192.       return true iff the string is junk.  The default is None, and is
  1193.       recommended; as of Python 2.3, an adaptive notion of "noise" lines is
  1194.       used that does a good job on its own.
  1195.  
  1196.     - charjunk: A function that should accept a string of length 1. The
  1197.       default is module-level function IS_CHARACTER_JUNK, which filters out
  1198.       whitespace characters (a blank or tab; note: bad idea to include newline
  1199.       in this!).
  1200.  
  1201.     Tools/scripts/ndiff.py is a command-line front-end to this function.
  1202.  
  1203.     Example:
  1204.  
  1205.     >>> diff = ndiff(\'one\\ntwo\\nthree\\n\'.splitlines(1),
  1206.     ...              \'ore\\ntree\\nemu\\n\'.splitlines(1))
  1207.     >>> print \'\'.join(diff),
  1208.     - one
  1209.     ?  ^
  1210.     + ore
  1211.     ?  ^
  1212.     - two
  1213.     - three
  1214.     ?  -
  1215.     + tree
  1216.     + emu
  1217.     '''
  1218.     return Differ(linejunk, charjunk).compare(a, b)
  1219.  
  1220.  
  1221. def _mdiff(fromlines, tolines, context = None, linejunk = None, charjunk = IS_CHARACTER_JUNK):
  1222.     '''Returns generator yielding marked up from/to side by side differences.
  1223.  
  1224.     Arguments:
  1225.     fromlines -- list of text lines to compared to tolines
  1226.     tolines -- list of text lines to be compared to fromlines
  1227.     context -- number of context lines to display on each side of difference,
  1228.                if None, all from/to text lines will be generated.
  1229.     linejunk -- passed on to ndiff (see ndiff documentation)
  1230.     charjunk -- passed on to ndiff (see ndiff documentation)
  1231.  
  1232.     This function returns an interator which returns a tuple:
  1233.     (from line tuple, to line tuple, boolean flag)
  1234.  
  1235.     from/to line tuple -- (line num, line text)
  1236.         line num -- integer or None (to indicate a context seperation)
  1237.         line text -- original line text with following markers inserted:
  1238.             \'\\0+\' -- marks start of added text
  1239.             \'\\0-\' -- marks start of deleted text
  1240.             \'\\0^\' -- marks start of changed text
  1241.             \'\\1\' -- marks end of added/deleted/changed text
  1242.  
  1243.     boolean flag -- None indicates context separation, True indicates
  1244.         either "from" or "to" line contains a change, otherwise False.
  1245.  
  1246.     This function/iterator was originally developed to generate side by side
  1247.     file difference for making HTML pages (see HtmlDiff class for example
  1248.     usage).
  1249.  
  1250.     Note, this function utilizes the ndiff function to generate the side by
  1251.     side difference markup.  Optional ndiff arguments may be passed to this
  1252.     function and they in turn will be passed to ndiff.
  1253.     '''
  1254.     import re as re
  1255.     change_re = re.compile('(\\++|\\-+|\\^+)')
  1256.     diff_lines_iterator = ndiff(fromlines, tolines, linejunk, charjunk)
  1257.     
  1258.     def _make_line(lines, format_key, side, num_lines = ([
  1259.         0,
  1260.         0],)):
  1261.         '''Returns line of text with user\'s change markup and line formatting.
  1262.  
  1263.         lines -- list of lines from the ndiff generator to produce a line of
  1264.                  text from.  When producing the line of text to return, the
  1265.                  lines used are removed from this list.
  1266.         format_key -- \'+\' return first line in list with "add" markup around
  1267.                           the entire line.
  1268.                       \'-\' return first line in list with "delete" markup around
  1269.                           the entire line.
  1270.                       \'?\' return first line in list with add/delete/change
  1271.                           intraline markup (indices obtained from second line)
  1272.                       None return first line in list with no markup
  1273.         side -- indice into the num_lines list (0=from,1=to)
  1274.         num_lines -- from/to current line number.  This is NOT intended to be a
  1275.                      passed parameter.  It is present as a keyword argument to
  1276.                      maintain memory of the current line numbers between calls
  1277.                      of this function.
  1278.  
  1279.         Note, this function is purposefully not defined at the module scope so
  1280.         that data it needs from its parent function (within whose context it
  1281.         is defined) does not need to be of module scope.
  1282.         '''
  1283.         num_lines[side] += 1
  1284.         if format_key is None:
  1285.             return (num_lines[side], lines.pop(0)[2:])
  1286.         
  1287.         if format_key == '?':
  1288.             text = lines.pop(0)
  1289.             markers = lines.pop(0)
  1290.             sub_info = []
  1291.             
  1292.             def record_sub_info(match_object, sub_info = sub_info):
  1293.                 sub_info.append([
  1294.                     match_object.group(1)[0],
  1295.                     match_object.span()])
  1296.                 return match_object.group(1)
  1297.  
  1298.             change_re.sub(record_sub_info, markers)
  1299.             for begin, end in sub_info[::-1]:
  1300.                 text = text[0:begin] + '\x00' + key + text[begin:end] + '\x01' + text[end:]
  1301.             
  1302.             text = text[2:]
  1303.         else:
  1304.             text = lines.pop(0)[2:]
  1305.             if not text:
  1306.                 text = ' '
  1307.             
  1308.             text = '\x00' + format_key + text + '\x01'
  1309.         return (num_lines[side], text)
  1310.  
  1311.     
  1312.     def _line_iterator():
  1313.         '''Yields from/to lines of text with a change indication.
  1314.  
  1315.         This function is an iterator.  It itself pulls lines from a
  1316.         differencing iterator, processes them and yields them.  When it can
  1317.         it yields both a "from" and a "to" line, otherwise it will yield one
  1318.         or the other.  In addition to yielding the lines of from/to text, a
  1319.         boolean flag is yielded to indicate if the text line(s) have
  1320.         differences in them.
  1321.  
  1322.         Note, this function is purposefully not defined at the module scope so
  1323.         that data it needs from its parent function (within whose context it
  1324.         is defined) does not need to be of module scope.
  1325.         '''
  1326.         lines = []
  1327.         (num_blanks_pending, num_blanks_to_yield) = (0, 0)
  1328.         for line in lines:
  1329.             continue
  1330.             s = _[1](_[1][line[0]])
  1331.             if s.startswith('X'):
  1332.                 num_blanks_to_yield = num_blanks_pending
  1333.             elif s.startswith('-?+?'):
  1334.                 yield (_make_line(lines, '?', 0), _make_line(lines, '?', 1), True)
  1335.                 []
  1336.                 continue
  1337.             elif s.startswith('--++'):
  1338.                 num_blanks_pending -= 1
  1339.                 yield (_make_line(lines, '-', 0), None, True)
  1340.                 continue
  1341.             elif s.startswith(('--?+', '--+', '- ')):
  1342.                 from_line = _make_line(lines, '-', 0)
  1343.                 to_line = None
  1344.                 num_blanks_to_yield = num_blanks_pending - 1
  1345.                 num_blanks_pending = 0
  1346.             elif s.startswith('-+?'):
  1347.                 yield (_make_line(lines, None, 0), _make_line(lines, '?', 1), True)
  1348.                 continue
  1349.             elif s.startswith('-?+'):
  1350.                 yield (_make_line(lines, '?', 0), _make_line(lines, None, 1), True)
  1351.                 continue
  1352.             elif s.startswith('-'):
  1353.                 num_blanks_pending -= 1
  1354.                 yield (_make_line(lines, '-', 0), None, True)
  1355.                 continue
  1356.             elif s.startswith('+--'):
  1357.                 num_blanks_pending += 1
  1358.                 yield (None, _make_line(lines, '+', 1), True)
  1359.                 continue
  1360.             elif s.startswith(('+ ', '+-')):
  1361.                 from_line = None
  1362.                 to_line = _make_line(lines, '+', 1)
  1363.                 num_blanks_to_yield = num_blanks_pending + 1
  1364.                 num_blanks_pending = 0
  1365.             elif s.startswith('+'):
  1366.                 num_blanks_pending += 1
  1367.                 yield (None, _make_line(lines, '+', 1), True)
  1368.                 continue
  1369.             elif s.startswith(' '):
  1370.                 yield (_make_line(lines[:], None, 0), _make_line(lines, None, 1), False)
  1371.                 continue
  1372.             
  1373.             while num_blanks_to_yield < 0:
  1374.                 num_blanks_to_yield += 1
  1375.                 yield (None, ('', '\n'), True)
  1376.             while num_blanks_to_yield > 0:
  1377.                 num_blanks_to_yield -= 1
  1378.                 yield (('', '\n'), None, True)
  1379.             if s.startswith('X'):
  1380.                 raise StopIteration
  1381.                 continue
  1382.             yield (from_line, to_line, True)
  1383.  
  1384.     
  1385.     def _line_pair_iterator():
  1386.         '''Yields from/to lines of text with a change indication.
  1387.  
  1388.         This function is an iterator.  It itself pulls lines from the line
  1389.         iterator.  Its difference from that iterator is that this function
  1390.         always yields a pair of from/to text lines (with the change
  1391.         indication).  If necessary it will collect single from/to lines
  1392.         until it has a matching pair from/to pair to yield.
  1393.  
  1394.         Note, this function is purposefully not defined at the module scope so
  1395.         that data it needs from its parent function (within whose context it
  1396.         is defined) does not need to be of module scope.
  1397.         '''
  1398.         line_iterator = _line_iterator()
  1399.         fromlines = []
  1400.         tolines = []
  1401.         while True:
  1402.             while len(fromlines) == 0 or len(tolines) == 0:
  1403.                 (from_line, to_line, found_diff) = line_iterator.next()
  1404.                 if from_line is not None:
  1405.                     fromlines.append((from_line, found_diff))
  1406.                 
  1407.                 if to_line is not None:
  1408.                     tolines.append((to_line, found_diff))
  1409.                     continue
  1410.             (from_line, fromDiff) = fromlines.pop(0)
  1411.             (to_line, to_diff) = tolines.pop(0)
  1412.             if not fromDiff:
  1413.                 pass
  1414.             yield (from_line, to_line, to_diff)
  1415.  
  1416.     line_pair_iterator = _line_pair_iterator()
  1417.     if context is None:
  1418.         while True:
  1419.             yield line_pair_iterator.next()
  1420.             ((None, None),)
  1421.     else:
  1422.         context += 1
  1423.         lines_to_write = 0
  1424.         while True:
  1425.             index = 0
  1426.             contextLines = [
  1427.                 None] * context
  1428.             found_diff = False
  1429.             while found_diff is False:
  1430.                 (from_line, to_line, found_diff) = line_pair_iterator.next()
  1431.                 i = index % context
  1432.                 contextLines[i] = (from_line, to_line, found_diff)
  1433.                 index += 1
  1434.                 continue
  1435.                 ((None, None),)
  1436.             if index > context:
  1437.                 yield (None, None, None)
  1438.                 lines_to_write = context
  1439.             else:
  1440.                 lines_to_write = index
  1441.                 index = 0
  1442.             while lines_to_write:
  1443.                 i = index % context
  1444.                 index += 1
  1445.                 yield contextLines[i]
  1446.                 lines_to_write -= 1
  1447.             lines_to_write = context - 1
  1448.             while lines_to_write:
  1449.                 (from_line, to_line, found_diff) = line_pair_iterator.next()
  1450.                 if found_diff:
  1451.                     lines_to_write = context - 1
  1452.                 else:
  1453.                     lines_to_write -= 1
  1454.                 yield (from_line, to_line, found_diff)
  1455.  
  1456. _file_template = '\n<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"\n          "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">\n\n<html>\n\n<head>\n    <meta http-equiv="Content-Type"\n          content="text/html; charset=ISO-8859-1" />\n    <title></title>\n    <style type="text/css">%(styles)s\n    </style>\n</head>\n\n<body>\n    %(table)s%(legend)s\n</body>\n\n</html>'
  1457. _styles = '\n        table.diff {font-family:Courier; border:medium;}\n        .diff_header {background-color:#e0e0e0}\n        td.diff_header {text-align:right}\n        .diff_next {background-color:#c0c0c0}\n        .diff_add {background-color:#aaffaa}\n        .diff_chg {background-color:#ffff77}\n        .diff_sub {background-color:#ffaaaa}'
  1458. _table_template = '\n    <table class="diff" id="difflib_chg_%(prefix)s_top"\n           cellspacing="0" cellpadding="0" rules="groups" >\n        <colgroup></colgroup> <colgroup></colgroup> <colgroup></colgroup>\n        <colgroup></colgroup> <colgroup></colgroup> <colgroup></colgroup>\n        %(header_row)s\n        <tbody>\n%(data_rows)s        </tbody>\n    </table>'
  1459. _legend = '\n    <table class="diff" summary="Legends">\n        <tr> <th colspan="2"> Legends </th> </tr>\n        <tr> <td> <table border="" summary="Colors">\n                      <tr><th> Colors </th> </tr>\n                      <tr><td class="diff_add"> Added </td></tr>\n                      <tr><td class="diff_chg">Changed</td> </tr>\n                      <tr><td class="diff_sub">Deleted</td> </tr>\n                  </table></td>\n             <td> <table border="" summary="Links">\n                      <tr><th colspan="2"> Links </th> </tr>\n                      <tr><td>(f)irst change</td> </tr>\n                      <tr><td>(n)ext change</td> </tr>\n                      <tr><td>(t)op</td> </tr>\n                  </table></td> </tr>\n    </table>'
  1460.  
  1461. class HtmlDiff(object):
  1462.     '''For producing HTML side by side comparison with change highlights.
  1463.  
  1464.     This class can be used to create an HTML table (or a complete HTML file
  1465.     containing the table) showing a side by side, line by line comparison
  1466.     of text with inter-line and intra-line change highlights.  The table can
  1467.     be generated in either full or contextual difference mode.
  1468.  
  1469.     The following methods are provided for HTML generation:
  1470.  
  1471.     make_table -- generates HTML for a single side by side table
  1472.     make_file -- generates complete HTML file with a single side by side table
  1473.  
  1474.     See tools/scripts/diff.py for an example usage of this class.
  1475.     '''
  1476.     _file_template = _file_template
  1477.     _styles = _styles
  1478.     _table_template = _table_template
  1479.     _legend = _legend
  1480.     _default_prefix = 0
  1481.     
  1482.     def __init__(self, tabsize = 8, wrapcolumn = None, linejunk = None, charjunk = IS_CHARACTER_JUNK):
  1483.         '''HtmlDiff instance initializer
  1484.  
  1485.         Arguments:
  1486.         tabsize -- tab stop spacing, defaults to 8.
  1487.         wrapcolumn -- column number where lines are broken and wrapped,
  1488.             defaults to None where lines are not wrapped.
  1489.         linejunk,charjunk -- keyword arguments passed into ndiff() (used to by
  1490.             HtmlDiff() to generate the side by side HTML differences).  See
  1491.             ndiff() documentation for argument default values and descriptions.
  1492.         '''
  1493.         self._tabsize = tabsize
  1494.         self._wrapcolumn = wrapcolumn
  1495.         self._linejunk = linejunk
  1496.         self._charjunk = charjunk
  1497.  
  1498.     
  1499.     def make_file(self, fromlines, tolines, fromdesc = '', todesc = '', context = False, numlines = 5):
  1500.         '''Returns HTML file of side by side comparison with change highlights
  1501.  
  1502.         Arguments:
  1503.         fromlines -- list of "from" lines
  1504.         tolines -- list of "to" lines
  1505.         fromdesc -- "from" file column header string
  1506.         todesc -- "to" file column header string
  1507.         context -- set to True for contextual differences (defaults to False
  1508.             which shows full differences).
  1509.         numlines -- number of context lines.  When context is set True,
  1510.             controls number of lines displayed before and after the change.
  1511.             When context is False, controls the number of lines to place
  1512.             the "next" link anchors before the next change (so click of
  1513.             "next" link jumps to just before the change).
  1514.         '''
  1515.         return self._file_template % dict(styles = self._styles, legend = self._legend, table = self.make_table(fromlines, tolines, fromdesc, todesc, context = context, numlines = numlines))
  1516.  
  1517.     
  1518.     def _tab_newline_replace(self, fromlines, tolines):
  1519.         '''Returns from/to line lists with tabs expanded and newlines removed.
  1520.  
  1521.         Instead of tab characters being replaced by the number of spaces
  1522.         needed to fill in to the next tab stop, this function will fill
  1523.         the space with tab characters.  This is done so that the difference
  1524.         algorithms can identify changes in a file when tabs are replaced by
  1525.         spaces and vice versa.  At the end of the HTML generation, the tab
  1526.         characters will be replaced with a nonbreakable space.
  1527.         '''
  1528.         
  1529.         def expand_tabs(line):
  1530.             line = line.replace(' ', '\x00')
  1531.             line = line.expandtabs(self._tabsize)
  1532.             line = line.replace(' ', '\t')
  1533.             return line.replace('\x00', ' ').rstrip('\n')
  1534.  
  1535.         fromlines = [ expand_tabs(line) for line in fromlines ]
  1536.         tolines = [ expand_tabs(line) for line in tolines ]
  1537.         return (fromlines, tolines)
  1538.  
  1539.     
  1540.     def _split_line(self, data_list, line_num, text):
  1541.         '''Builds list of text lines by splitting text lines at wrap point
  1542.  
  1543.         This function will determine if the input text line needs to be
  1544.         wrapped (split) into separate lines.  If so, the first wrap point
  1545.         will be determined and the first line appended to the output
  1546.         text line list.  This function is used recursively to handle
  1547.         the second part of the split line to further split it.
  1548.         '''
  1549.         if not line_num:
  1550.             data_list.append((line_num, text))
  1551.             return None
  1552.         
  1553.         size = len(text)
  1554.         max = self._wrapcolumn
  1555.         if size <= max or size - text.count('\x00') * 3 <= max:
  1556.             data_list.append((line_num, text))
  1557.             return None
  1558.         
  1559.         i = 0
  1560.         n = 0
  1561.         mark = ''
  1562.         while n < max and i < size:
  1563.             if text[i] == '\x00':
  1564.                 i += 1
  1565.                 mark = text[i]
  1566.                 i += 1
  1567.                 continue
  1568.             if text[i] == '\x01':
  1569.                 i += 1
  1570.                 mark = ''
  1571.                 continue
  1572.             i += 1
  1573.             n += 1
  1574.         line1 = text[:i]
  1575.         line2 = text[i:]
  1576.         if mark:
  1577.             line1 = line1 + '\x01'
  1578.             line2 = '\x00' + mark + line2
  1579.         
  1580.         data_list.append((line_num, line1))
  1581.         self._split_line(data_list, '>', line2)
  1582.  
  1583.     
  1584.     def _line_wrapper(self, diffs):
  1585.         '''Returns iterator that splits (wraps) mdiff text lines'''
  1586.         for fromdata, todata, flag in diffs:
  1587.             if flag is None:
  1588.                 yield (fromdata, todata, flag)
  1589.                 continue
  1590.             
  1591.             (fromline, fromtext) = fromdata
  1592.             (toline, totext) = todata
  1593.             fromlist = []
  1594.             tolist = []
  1595.             self._split_line(fromlist, fromline, fromtext)
  1596.             self._split_line(tolist, toline, totext)
  1597.             while fromlist or tolist:
  1598.                 if fromlist:
  1599.                     fromdata = fromlist.pop(0)
  1600.                 else:
  1601.                     fromdata = ('', ' ')
  1602.                 if tolist:
  1603.                     todata = tolist.pop(0)
  1604.                 else:
  1605.                     todata = ('', ' ')
  1606.                 yield (fromdata, todata, flag)
  1607.         
  1608.  
  1609.     
  1610.     def _collect_lines(self, diffs):
  1611.         '''Collects mdiff output into separate lists
  1612.  
  1613.         Before storing the mdiff from/to data into a list, it is converted
  1614.         into a single line of text with HTML markup.
  1615.         '''
  1616.         fromlist = []
  1617.         tolist = []
  1618.         flaglist = []
  1619.         for fromdata, todata, flag in diffs:
  1620.             
  1621.             try:
  1622.                 fromlist.append(self._format_line(0, flag, *fromdata))
  1623.                 tolist.append(self._format_line(1, flag, *todata))
  1624.             except TypeError:
  1625.                 fromlist.append(None)
  1626.                 tolist.append(None)
  1627.  
  1628.             flaglist.append(flag)
  1629.         
  1630.         return (fromlist, tolist, flaglist)
  1631.  
  1632.     
  1633.     def _format_line(self, side, flag, linenum, text):
  1634.         '''Returns HTML markup of "from" / "to" text lines
  1635.  
  1636.         side -- 0 or 1 indicating "from" or "to" text
  1637.         flag -- indicates if difference on line
  1638.         linenum -- line number (used for line number column)
  1639.         text -- line text to be marked up
  1640.         '''
  1641.         
  1642.         try:
  1643.             linenum = '%d' % linenum
  1644.             id = ' id="%s%s"' % (self._prefix[side], linenum)
  1645.         except TypeError:
  1646.             id = ''
  1647.  
  1648.         text = text.replace('&', '&').replace('>', '>').replace('<', '<')
  1649.         text = text.replace(' ', ' ').rstrip()
  1650.         return '<td class="diff_header"%s>%s</td><td nowrap="nowrap">%s</td>' % (id, linenum, text)
  1651.  
  1652.     
  1653.     def _make_prefix(self):
  1654.         '''Create unique anchor prefixes'''
  1655.         fromprefix = 'from%d_' % HtmlDiff._default_prefix
  1656.         toprefix = 'to%d_' % HtmlDiff._default_prefix
  1657.         HtmlDiff._default_prefix += 1
  1658.         self._prefix = [
  1659.             fromprefix,
  1660.             toprefix]
  1661.  
  1662.     
  1663.     def _convert_flags(self, fromlist, tolist, flaglist, context, numlines):
  1664.         '''Makes list of "next" links'''
  1665.         toprefix = self._prefix[1]
  1666.         next_id = [
  1667.             ''] * len(flaglist)
  1668.         next_href = [
  1669.             ''] * len(flaglist)
  1670.         num_chg = 0
  1671.         in_change = False
  1672.         last = 0
  1673.         for i, flag in enumerate(flaglist):
  1674.             if flag:
  1675.                 if not in_change:
  1676.                     in_change = True
  1677.                     last = i
  1678.                     i = max([
  1679.                         0,
  1680.                         i - numlines])
  1681.                     next_id[i] = ' id="difflib_chg_%s_%d"' % (toprefix, num_chg)
  1682.                     num_chg += 1
  1683.                     next_href[last] = '<a href="#difflib_chg_%s_%d">n</a>' % (toprefix, num_chg)
  1684.                 
  1685.             in_change
  1686.             in_change = False
  1687.         
  1688.         if not flaglist:
  1689.             flaglist = [
  1690.                 False]
  1691.             next_id = [
  1692.                 '']
  1693.             next_href = [
  1694.                 '']
  1695.             last = 0
  1696.             if context:
  1697.                 fromlist = [
  1698.                     '<td></td><td> No Differences Found </td>']
  1699.                 tolist = fromlist
  1700.             else:
  1701.                 fromlist = tolist = [
  1702.                     '<td></td><td> Empty File </td>']
  1703.         
  1704.         if not flaglist[0]:
  1705.             next_href[0] = '<a href="#difflib_chg_%s_0">f</a>' % toprefix
  1706.         
  1707.         next_href[last] = '<a href="#difflib_chg_%s_top">t</a>' % toprefix
  1708.         return (fromlist, tolist, flaglist, next_href, next_id)
  1709.  
  1710.     
  1711.     def make_table(self, fromlines, tolines, fromdesc = '', todesc = '', context = False, numlines = 5):
  1712.         '''Returns HTML table of side by side comparison with change highlights
  1713.  
  1714.         Arguments:
  1715.         fromlines -- list of "from" lines
  1716.         tolines -- list of "to" lines
  1717.         fromdesc -- "from" file column header string
  1718.         todesc -- "to" file column header string
  1719.         context -- set to True for contextual differences (defaults to False
  1720.             which shows full differences).
  1721.         numlines -- number of context lines.  When context is set True,
  1722.             controls number of lines displayed before and after the change.
  1723.             When context is False, controls the number of lines to place
  1724.             the "next" link anchors before the next change (so click of
  1725.             "next" link jumps to just before the change).
  1726.         '''
  1727.         self._make_prefix()
  1728.         (fromlines, tolines) = self._tab_newline_replace(fromlines, tolines)
  1729.         if context:
  1730.             context_lines = numlines
  1731.         else:
  1732.             context_lines = None
  1733.         diffs = _mdiff(fromlines, tolines, context_lines, linejunk = self._linejunk, charjunk = self._charjunk)
  1734.         if self._wrapcolumn:
  1735.             diffs = self._line_wrapper(diffs)
  1736.         
  1737.         (fromlist, tolist, flaglist) = self._collect_lines(diffs)
  1738.         (fromlist, tolist, flaglist, next_href, next_id) = self._convert_flags(fromlist, tolist, flaglist, context, numlines)
  1739.         s = []
  1740.         fmt = '            <tr><td class="diff_next"%s>%s</td>%s' + '<td class="diff_next">%s</td>%s</tr>\n'
  1741.         for i in range(len(flaglist)):
  1742.             if flaglist[i] is None:
  1743.                 if i > 0:
  1744.                     s.append('        </tbody>        \n        <tbody>\n')
  1745.                 
  1746.             i > 0
  1747.             s.append(fmt % (next_id[i], next_href[i], fromlist[i], next_href[i], tolist[i]))
  1748.         
  1749.         if fromdesc or todesc:
  1750.             header_row = '<thead><tr>%s%s%s%s</tr></thead>' % ('<th class="diff_next"><br /></th>', '<th colspan="2" class="diff_header">%s</th>' % fromdesc, '<th class="diff_next"><br /></th>', '<th colspan="2" class="diff_header">%s</th>' % todesc)
  1751.         else:
  1752.             header_row = ''
  1753.         table = self._table_template % dict(data_rows = ''.join(s), header_row = header_row, prefix = self._prefix[1])
  1754.         return table.replace('\x00+', '<span class="diff_add">').replace('\x00-', '<span class="diff_sub">').replace('\x00^', '<span class="diff_chg">').replace('\x01', '</span>').replace('\t', ' ')
  1755.  
  1756.  
  1757. del re
  1758.  
  1759. def restore(delta, which):
  1760.     """
  1761.     Generate one of the two sequences that generated a delta.
  1762.  
  1763.     Given a `delta` produced by `Differ.compare()` or `ndiff()`, extract
  1764.     lines originating from file 1 or 2 (parameter `which`), stripping off line
  1765.     prefixes.
  1766.  
  1767.     Examples:
  1768.  
  1769.     >>> diff = ndiff('one\\ntwo\\nthree\\n'.splitlines(1),
  1770.     ...              'ore\\ntree\\nemu\\n'.splitlines(1))
  1771.     >>> diff = list(diff)
  1772.     >>> print ''.join(restore(diff, 1)),
  1773.     one
  1774.     two
  1775.     three
  1776.     >>> print ''.join(restore(diff, 2)),
  1777.     ore
  1778.     tree
  1779.     emu
  1780.     """
  1781.     
  1782.     try:
  1783.         tag = {
  1784.             1: '- ',
  1785.             2: '+ ' }[int(which)]
  1786.     except KeyError:
  1787.         raise ValueError, 'unknown delta choice (must be 1 or 2): %r' % which
  1788.  
  1789.     prefixes = ('  ', tag)
  1790.     for line in delta:
  1791.         if line[:2] in prefixes:
  1792.             yield line[2:]
  1793.             continue
  1794.     
  1795.  
  1796.  
  1797. def _test():
  1798.     import doctest as doctest
  1799.     import difflib as difflib
  1800.     return doctest.testmod(difflib)
  1801.  
  1802. if __name__ == '__main__':
  1803.     _test()
  1804.  
  1805.